﻿using System;
using System.Web;
using Web.Model;
using NHibernate;
using Web.Extensions;
using System.Web.Mvc;

namespace Web.HelperClasses
{
    public class NewsNotifier
    {
        private News news;
        private ISession session;
        private User author;

        private const string NewCommentTemplate = @"Уважаемый {0}. <br/>
В обсуждении Вашей новости <a href='{2}'>{1}</a><br/>
Пользователь <a href='{4}'>{3}</a> добавил комментарий:<br/>
<br/>
{5}<br/>";

        public NewsNotifier(int id, ISession session)
        {
            this.session = session;
            news = session.Get<News>(id);
            if (news == null) throw new InvalidOperationException("Новость не найдена");
            author = news.Author;
            if (author == null) throw new InvalidOperationException("Пользователь не найден");
        }

        public NewsNotifier(News news, ISession session)
        {
            this.session = session;
            this.news = news;
            author = news.Author;
            if (author == null) throw new InvalidOperationException("Пользователь не найден");
        }

        public void NotifyNewComment(CommentBase newComment)
        {
            if (author.NotifyAuthorNewsCommented && !String.IsNullOrEmpty(author.Email))
            {
                UrlHelper urlHelper = UrlHelperExtensions.GetUrlHelper();
                Notification newNotification = new Notification()
                {
                    Subject = "Новый комментарий к новости '" + news.Title + "'",
                    // Recipient = organizer,
                    Email = author.NotificationEmail,
                    Body = String.Format(NewCommentTemplate,
                        HttpUtility.HtmlEncode(author.DisplayName),
                        HttpUtility.HtmlEncode(news.Title),
                        urlHelper.ActionAbsolute("View", "News", new { Id = news.Id }).AbsoluteUri,
                        HttpUtility.HtmlEncode(newComment.Author.DisplayName),
                        urlHelper.ActionAbsolute("View", "User", new { Id = newComment.Author.Id }).AbsoluteUri,
                        HttpUtility.HtmlEncode(newComment.Text)
                    )
                };
                session.Save(newNotification);
            }
        }
    }
}